<template>
    <div>
        <div class="mb-2">
            <el-button type="primary" icon="Edit" @click="showNew" v-perm="'edit'">编辑</el-button>
        </div>
        <data-table :fields="fields" v-model="appDepts" height="calc(100vh - 500px)"></data-table>

        <el-dialog title="添加机构" width="400px" v-model="visible" destroy-on-close>
            <base-form :fields="formFields" v-model="form" ref="formRef"></base-form>
            <template #footer>
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="save">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import dataTable from "@/components/base-table/data-table.vue";
import { computed, onMounted } from "vue";

const { appId } = defineProps({
    appId: String,
});
const fields = [{ label: "机构名称", prop: "name" }];
const depts = ref([]);
const visible = ref(false);
const form = ref({});
const formRef = ref();
const formFields = [{ label: "机构", prop: "depts", type: "treeSelect", options: () => depts.value, multiple: true, required: false }];
const deptIds = ref([]);
const appDepts = computed(() => {
    let result = [];
    app.utils.loop(depts.value, (item) => {
        if (deptIds.value.includes(item.id)) {
            result.push({
                name: item.name,
                id: item.id,
            });
        }
    });

    return result;
});

onMounted(() => {
    loadDepts();
    loadAppDepts();
});

function loadDepts() {
    app.https.get("/sys/dept/tree").then((resp) => {
        depts.value = resp;
    });
}

function loadAppDepts() {
    app.https.post("/sys/dept-app/query", { appId }).then((resp) => {
        deptIds.value = resp.map((item) => item.deptId);
    });
}

function showNew() {
    form.value.depts = deptIds.value;
    visible.value = true;
}

function save() {
    formRef.value.validate((res) => {
        if (!res) {
            return;
        }

        app.https
            .post("/sys/dept-app/update-dept-app", {
                appId,
                deptIds: form.value.depts,
            })
            .then(() => {
                app.success("操作成功");
                visible.value = false;
                loadAppDepts();
            });
    });
}
</script>

<style lang="scss" scoped></style>
